package user

import (
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"shangyuapi/data_source"
	"shangyuapi/models"
	"strings"
	"time"
)

func Userlist(ctx *gin.Context) {
	request := UserinfoBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid
	inttime, _ := getCurrentdayStartAndEnd()

	var userdaylist []models.Userday
	data_source.Db.Where("uid = ?", uid).Where("daytime = ?", inttime).Find(&userdaylist)
	if len(userdaylist) > 0 {
		var uidarr []int64
		for _, v := range userdaylist {
			uidarr = append(uidarr, v.Userid)
		}
		var userlistone []models.User
		data_source.Db.Select("id,nickname,city,logo,shengri,name,xingzuo,height,weight,career,company,income,education,province,school,nationality,huji,children,marriage,belief,smoke,wine,biaoqian,title,family,love,images").Where("id in (?)", uidarr).Find(&userlistone)

		// 初始化随机数种子
		//rand.Seed(time.Now().UnixNano())
		for k, v := range userlistone {
			for _, u := range userdaylist {
				if v.ID == u.Userid {
					userlistone[k].Pipeidui = u.Pipeidui
				}
			}

		}

		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    userlistone,
			"msg":     "ok",
		})
		return
	} else {
		var user models.User
		data_source.Db.Select("id,agemax,agemin,sex").Where("id = ?", uid).First(&user)
		//data_source.Db.Model(&models.User{}).Where("id = ?", uid).Update("updatetime", time.Now().Unix())

		var sex int64
		if user.Sex == 1 {
			sex = 2
		} else {
			sex = 1
		}
		var userlike []models.Userlike
		data_source.Db.Where("userid = ?", uid).Where("daytime = ?", inttime-86400).Where("state = 1").Find(&userlike)

		var userliketwo []models.Userlike
		data_source.Db.Where("uid = ?", uid).Find(&userliketwo)

		var userlike3 []models.Userlike
		data_source.Db.Where("userid = ?", uid).Where("state = 2").Find(&userlike3)

		var useridarr []int64
		var useridarrtwo []int64
		for _, v := range userlike {
			cunzai := 1
			for _, u := range userliketwo {
				if v.Uid == u.Userid {
					cunzai = 2
				}
			}
			if cunzai == 1 {
				useridarr = append(useridarr, v.Uid)
			}
		}
		for _, u := range userliketwo {
			useridarrtwo = append(useridarrtwo, u.Userid)
		}
		for _, u := range userlike3 {
			useridarrtwo = append(useridarrtwo, u.Userid)
		}
		var userlist []models.User
		if len(useridarr) > 0 {
			data_source.Db.Select("id,nickname,city,logo,shengri,name,xingzuo,height,weight,career,company,income,education,province,school,nationality,huji,children,marriage,belief,smoke,wine,biaoqian,title,family,love,images").Where("id in (?)", useridarr).Where("sex = ?", sex).Where("age >= ?", user.Agemin).Where("age <= ?", user.Agemax).Where("shenhe = 3").Limit(5).Find(&userlist)
		}

		var userlisttwo []models.User
		var userlist3 []models.User

		num := len(userlist)
		if num == 5 {
			userlisttwo = userlist
		} else if num > 0 && num < 5 {
			userlisttwo = userlist
			if len(useridarrtwo) > 0 {
				data_source.Db.Select("id,nickname,city,logo,shengri,name,xingzuo,height,weight,career,company,income,education,province,school,nationality,huji,children,marriage,belief,smoke,wine,biaoqian,title,family,love,images").Where("id not in (?)", useridarrtwo).Where("sex = ?", sex).Where("age >= ?", user.Agemin).Where("age <= ?", user.Agemax).Where("shenhe = 3").Limit(5 - num).Find(&userlist3)
			} else {
				data_source.Db.Select("id,nickname,city,logo,shengri,name,xingzuo,height,weight,career,company,income,education,province,school,nationality,huji,children,marriage,belief,smoke,wine,biaoqian,title,family,love,images").Where("sex = ?", sex).Where("age >= ?", user.Agemin).Where("age <= ?", user.Agemax).Where("shenhe = 3").Limit(5 - num).Find(&userlist3)
			}
			for _, u3 := range userlist3 {
				userlisttwo = append(userlisttwo, u3)
			}

		} else if len(useridarr) == 0 {
			if len(useridarrtwo) > 0 {
				data_source.Db.Select("id,nickname,city,logo,shengri,name,xingzuo,height,weight,career,company,income,education,province,school,nationality,huji,children,marriage,belief,smoke,wine,biaoqian,title,family,love,images").Where("id not in (?)", useridarrtwo).Where("age >= ?", user.Agemin).Where("age <= ?", user.Agemax).Where("shenhe = 3").Limit(5).Find(&userlisttwo)
			} else {
				data_source.Db.Select("id,nickname,city,logo,shengri,name,xingzuo,height,weight,career,company,income,education,province,school,nationality,huji,children,marriage,belief,smoke,wine,biaoqian,title,family,love,images").Where("sex = ?", sex).Where("age >= ?", user.Agemin).Where("age <= ?", user.Agemax).Where("shenhe = 3").Limit(5).Find(&userlisttwo)
			}
		}

		// 初始化随机数种子
		rand.Seed(time.Now().UnixNano())

		var userdays []models.Userday

		for k, v := range userlisttwo {
			// 生成随机数
			randomNumber := rand.Intn(15) + 85
			userlisttwo[k].Pipeidui = int64(randomNumber)

			userday := models.Userday{
				Uid:      uid,
				Userid:   v.ID,
				Daytime:  inttime,
				Pipeidui: int64(randomNumber),
			}
			userdays = append(userdays, userday)
		}
		data_source.Db.Create(&userdays)
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    userlisttwo,
			"msg":     "ok",
		})
		return
	}

}

func Userlikeinfobuyprice(ctx *gin.Context) {
	var config models.Config
	data_source.Db.Where("id = ?", 2).First(&config)

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    config,
		"msg":     "ok",
	})
	return

}
func Userlikeinfobuy(ctx *gin.Context) {
	request := UserlikeBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid

	//data_source.Db.Model(&models.User{}).Where("id = ?", uid).Update("updatetime", time.Now().Unix())

	userid := request.Userid
	inttime, _ := getCurrentdayStartAndEnd()
	var usersee models.Usersee
	data_source.Db.Where("userid = ?", userid).Where("status = 2").Where("uid = ?", uid).First(&usersee)
	if usersee.ID > 0 {
		var user models.User
		data_source.Db.Where("id = ?", userid).First(&user)

		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    user,
			"msg":     "ok",
		})
		return
	} else {
		var userinfo models.User
		data_source.Db.Where("id = ?", uid).First(&userinfo)
		var config models.Config
		data_source.Db.Where("id = ?", 2).First(&config)
		if userinfo.Xingbi < float64(config.Value) {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    400,
				"error":   1,
				"success": 400,
				"data":    "on",
				"msg":     "星币不足",
			})
			return
		}

		xingbi := models.Userxingbi{
			Uid:     uid,
			Price:   float64(config.Value),
			Status:  2,
			Title:   "查看异性详情",
			Addtime: time.Now().Unix(),
			Dqprice: userinfo.Xingbi - float64(config.Value),
		}
		data_source.Db.Create(&xingbi)

		data_source.Db.Model(&models.User{}).Where("id = ?", uid).Update("xingbi", userinfo.Xingbi-float64(config.Value))

		userseead := models.Usersee{
			Uid:     uid,
			Userid:  userid,
			Daytime: inttime,
			Status:  2,
			Price:   float64(config.Value),
		}
		data_source.Db.Create(&userseead)

		var user models.User
		data_source.Db.Where("id = ?", userid).First(&user)

		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    user,
			"msg":     "ok",
		})
		return

	}

}
func Userlikeinfo(ctx *gin.Context) {
	request := UserlikeBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid
	userid := request.Userid

	//data_source.Db.Model(&models.User{}).Where("id = ?", uid).Update("updatetime", time.Now().Unix())

	inttime, _ := getCurrentdayStartAndEnd()
	var usersee models.Usersee
	data_source.Db.Where("daytime = ?", inttime).Where("userid = ?", userid).Where("status = 2").Where("uid = ?", uid).First(&usersee)
	if usersee.ID > 0 {
		var user models.User
		data_source.Db.Select("id,nickname,city,logo,shengri,name,xingzuo,height,weight,career,company,income,education,province,school,nationality,huji,children,marriage,belief,smoke,wine,biaoqian,title,family,love,images").Where("id = ?", userid).First(&user)

		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    user,
			"msg":     "ok",
		})
		return
	} else {
		var usersees []models.Usersee
		data_source.Db.Where("daytime = ?", inttime).Where("status = 2").Where("uid = ?", uid).Find(&usersees)
		if len(usersees) < 2 {
			userseead := models.Usersee{
				Uid:     uid,
				Userid:  userid,
				Daytime: inttime,
				Status:  2,
				Price:   0,
			}
			data_source.Db.Create(&userseead)
			var user models.User
			data_source.Db.Select("id,nickname,city,logo,shengri,name,xingzuo,height,weight,career,company,income,education,province,school,nationality,huji,children,marriage,belief,smoke,wine,biaoqian,title,family,love,images").Where("id = ?", userid).First(&user)

			ctx.JSON(http.StatusOK, gin.H{
				"code":    0,
				"error":   0,
				"success": 200,
				"data":    user,
				"msg":     "ok",
			})
			return
		} else {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    400,
				"error":   1,
				"success": 400,
				"data":    "on",
				"msg":     "支付查看",
			})
			return
		}
	}

}

type UserlikeBody struct {
	Uid      int64 `json:"uid" gorm:"uid"`
	Userid   int64 `json:"userid" gorm:"userid"`
	State    int64 `json:"state" gorm:"state"` // 1感兴趣 2不感兴趣
	PageNo   int   `json:"pageNo"`
	Pagesize int   `json:"pagesize"`
	Paixu    int64 `json:"paixu"`
	Cityid   int64 `json:"cityid"`
}

type HongniangsRBody struct {
	Data       []models.Hongniang `json:"data"`
	PageNo     int                `json:"pageNo"`
	PageSize   int                `json:"pageSize"`
	TotalCount int64              `json:"totalCount"`
	TotalPage  int64              `json:"totalPage"`
}

func Hongnianglist(ctx *gin.Context) {
	request := UserlikeBody{}
	ctx.ShouldBind(&request)
	userid := request.Userid
	paixu := request.Paixu
	cityid := request.Cityid

	currentPage := request.PageNo
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	var users []models.Hongniang
	res := data_source.Db.Where("yuyuedan = 2")
	if userid > 0 {
		var user models.User
		data_source.Db.Where("id = ?", userid).First(&user)
		res = res.Where("cityid = ?", user.Cityid)
	} else {
		if cityid > 0 {
			res = res.Where("cityid = ?", cityid)
		}
	}

	res.Model(&models.Hongniang{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum)
	if paixu == 0 || paixu == 1 {
		res = res.Order("id desc").Find(&users)
	} else {
		res = res.Order("id desc").Find(&users)
	}

	var hongniangidarr []int64
	for _, h := range users {
		hongniangidarr = append(hongniangidarr, h.ID)
	}

	var fuwus []models.Hongniangfuwusql
	data_source.Db.Model(&models.Hongniangfuwu{}).Select("hongniangfuwu.*, fuwu.name").Joins("left join fuwu on fuwu.id = hongniangfuwu.fuwuid").Where("hongniangfuwu.hongniangid in (?)", hongniangidarr).Find(&fuwus)
	rand.Seed(time.Now().UnixNano())
	for k, v := range users {
		// 生成6000到9000之间的随机数
		randomNumber := rand.Intn(3000) + 6000
		randomNumber1 := rand.Intn(3000) + 6000
		randomNumber2 := rand.Intn(3000) + 6000
		users[k].Bangzhu = int64(randomNumber)
		users[k].Hour = int64(randomNumber1)
		users[k].Pingjianum = int64(randomNumber2)
		var fuwuarr []string
		for _, f := range fuwus {
			if v.ID == f.Hongniangid {
				fuwuarr = append(fuwuarr, f.Name)
			}
		}
		users[k].Fuwus = strings.Join(fuwuarr, ",")
	}

	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := HongniangsRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return
}
func Userlike(ctx *gin.Context) {
	request := UserlikeBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid
	userid := request.Userid
	state := request.State
	inttime, _ := getCurrentdayStartAndEnd()
	like := models.Userlike{
		Userid:  userid,
		Uid:     uid,
		Daytime: inttime,
		State:   state,
	}
	data_source.Db.Create(&like)
	if state == 1 {
		var likeinfo models.Userlike
		data_source.Db.Where("userid = ?", uid).Where("uid = ?", userid).Where("state = 1").First(&likeinfo)
		if likeinfo.ID > 0 {
			var fuwu models.Fuwu
			data_source.Db.Where("id = 2").First(&fuwu)
			orderadd := models.Orders{
				Uid:         uid,
				Userid:      userid,
				Hongniangid: 0,
				Status:      1,
				Addtime:     time.Now().UnixNano(),
				Uprice:      fuwu.Price,
				Userprice:   fuwu.Price,
				Fwprice:     fuwu.Price + fuwu.Price,
				Price:       fuwu.Price + fuwu.Price,
				Yhprice:     0,
				State:       1,
				Fuwu:        "1v1约会",
			}
			data_source.Db.Create(&orderadd)
		}
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}

type UserlistRBody struct {
	Data       []models.User `json:"data"`
	PageNo     int           `json:"pageNo"`
	PageSize   int           `json:"pageSize"`
	TotalCount int64         `json:"totalCount"`
	TotalPage  int64         `json:"totalPage"`
}

type UserlistBody struct {
	Uid      int `json:"uid"`
	State    int `json:"state"`
	Page     int `json:"page"`
	Pagesize int `json:"pagesize"`
}

func Userlikelist(ctx *gin.Context) {
	request := UserlistBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid
	state := request.State
	var userlike []models.Userlike
	var useridarr []int64
	if state == 1 {
		data_source.Db.Where("uid = ?", uid).Where("state = 1").Find(&userlike)
		for _, v := range userlike {
			useridarr = append(useridarr, v.Userid)
		}
	} else {
		data_source.Db.Where("userid = ?", uid).Where("state = 1").Find(&userlike)
		for _, v := range userlike {
			useridarr = append(useridarr, v.Uid)
		}
	}

	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	var users []models.User
	res := data_source.Db.Where("id in (?)", useridarr)
	res.Model(&models.User{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Find(&users)
	var usersees []models.Usersee
	data_source.Db.Where("userid in (?)", useridarr).Where("uid = ?", uid).Where("status = 2").Find(&usersees)
	for k, u := range users {
		users[k].Dianliang = 1
		for _, us := range usersees {
			if u.ID == us.Userid {
				users[k].Dianliang = 2
			}
		}
	}

	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := UserlistRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return
}

type FatanglistRBody struct {
	Data       []models.Fatang `json:"data"`
	PageNo     int             `json:"pageNo"`
	PageSize   int             `json:"pageSize"`
	TotalCount int64           `json:"totalCount"`
	TotalPage  int64           `json:"totalPage"`
}

func Fatanglist(ctx *gin.Context) {
	request := UserlistBody{}
	ctx.ShouldBind(&request)
	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	var users []models.Fatang
	res := data_source.Db
	res.Model(&models.Fatang{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("id desc").Find(&users)
	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := FatanglistRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return
}

type FatangBody struct {
	ID      int64  `json:"id"`
	Uid     int64  `json:"uid"`
	Orderid int64  `json:"orderid"`
	Nanid   int64  `json:"nanid" gorm:"nanid"`
	Nvid    int64  `json:"nvid" gorm:"nvid"`
	Nanname string `json:"nanname" gorm:"nanname"`
	Nanlogo string `json:"nanlogo" gorm:"nanlogo"`
	Nvname  string `json:"nvname" gorm:"nvname"`
	Nvlogo  string `json:"nvlogo" gorm:"nvlogo"`
	Title   string `json:"title" gorm:"title"`     //红娘描述
	Content string `json:"content" gorm:"content"` //详细描述
	Images  string `json:"images" gorm:"images"`
}

func Fatanginfo(ctx *gin.Context) {
	request := FatangBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	var fatang models.Fatang
	data_source.Db.Where("id = ?", id).First(&fatang)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    fatang,
		"msg":     "ok",
	})
	return
}

func Fatangadd(ctx *gin.Context) {
	request := FatangBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid
	orderid := request.Orderid
	content := request.Content
	images := request.Images
	var order models.Orders
	data_source.Db.Where("id = ?", orderid).First(&order)

	var userid int64
	var nanid int64
	var nvid int64
	var nanname string
	var nanlogo string
	var nvname string
	var nvlogo string
	if order.Uid == uid {
		userid = order.Userid
	} else if order.Userid == uid {
		userid = order.Uid
	} else {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "您无法给该订单发糖",
		})
		return
	}

	var u models.User
	data_source.Db.Where("id = ?", uid).First(&u)
	var user models.User
	data_source.Db.Where("id = ?", userid).First(&user)

	if u.Sex == 1 {
		nanid = u.ID
		nanname = u.Nickname
		nanlogo = u.Logo
		nvid = user.ID
		nvlogo = user.Logo
		nvname = user.Nickname
	} else {
		nvid = u.ID
		nvname = u.Nickname
		nvlogo = u.Logo
		nanid = user.ID
		nanlogo = user.Logo
		nanname = user.Nickname
	}

	fatangadd := models.Fatang{
		Addtime:     time.Now().Unix(),
		Nanid:       nanid,
		Nanlogo:     nanlogo,
		Nanname:     nanname,
		Nvid:        nvid,
		Nvlogo:      nvlogo,
		Nvname:      nvname,
		Content:     content,
		Images:      images,
		Hongniangid: order.Hongniangid,
		Title:       order.Hntitle,
	}
	data_source.Db.Create(&fatangadd)
	data_source.Db.Model(&models.Orders{}).Where("id = ?", orderid).Update("status", 8)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}

// 今天开始结束时间戳
func getCurrentdayStartAndEnd() (startTime, endTime int64) {
	// 获取当前时间
	//今天开始
	startOfToday := time.Now().Truncate(24 * time.Hour)
	startTimestamp := startOfToday.Unix() - 28800
	// 获取今天的结束时间
	endOfToday := startOfToday.Add(24 * time.Hour).Add(-1 * time.Second)
	endTimestamp := endOfToday.Unix() - 28800

	return startTimestamp, endTimestamp
}
